const process = require('process')
const puppeteer = require('puppeteer')
const {username, password} = require('./config.json')
const siteurl = 'http://10.51.3.40/'

async function run() {
    const browser = await puppeteer.launch({
        headless: true,
        args: ['--no-sandbox', '--disable-setuid-sandbox']
    })
    const page = await browser.newPage()
    await page.setViewport({
        width: 1024, height: 768, deviceScaleFactor: 1
    })
    await page.setJavaScriptEnabled(true)
    await page.goto(siteurl)
    page.on('response', resp => {
        console.log(resp.url())
    })
    //await page.screenshot({path: 'login.png'})
    // http://10.51.3.40/srun_portal_success?ac_id=2&theme=basic1
    // http://10.51.3.40/srun_portal_pc?ac_id=2&theme=basic1
    if (check_url(page)) {
        console.log('Already login')
    } else {
        console.log('Not login, begin to login...')
        await login(page)
    }
	await browser.close()
}

// function check_url, check the pattern of url in page
// if url path starts with srun_portal_success, return true
// else return false
function check_url(page) {
    return page.url().startsWith(siteurl + 'srun_portal_success')
}

async function login(page) {
    await page.evaluate((username, password) => {
        document.getElementById('username').value = username
        document.getElementById('password').value = password
        document.getElementById('login-account').click()
    }, username, password)
    await page.waitForResponse(resp => {
        console.log('Wait for login response...')
        console.log(resp.url())
        return resp.status() === 200
    })
    await page.waitForSelector('.panel-row')
    //await page.screenshot({path: 'first.png'})
    const status = await page.evaluate(() => {
        let result = ''
        document.querySelectorAll('.panel-row').forEach(val => result += val.textContent.trim())
        return result
    })
	// console.log(status)
}

run().catch(err => {
    console.log(err)
    process.exit(1)
})
